package com.enjoy.concurrent.ch6;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ScheduledExecutorServiceTest {

    static int i = 0;

    static ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1, new CustomThreadFactory("schedule"));

    static ExecutorService executorService = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors() * 2,
            5,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(8),
            new ThreadFactory() {
                AtomicInteger i = new AtomicInteger();

                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "pool-" + i.incrementAndGet());
                }
            },
            new RejectedExecutionHandler() {
                private AtomicInteger i = new AtomicInteger();

                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    new Thread(r, "mpi-extend-" + i.incrementAndGet()).start();
                }
            }
    );

    public static void main(String[] args) {
        scheduledExecutorService.scheduleAtFixedRate(new CheckRedis(), 1, 5, TimeUnit.SECONDS);
    }


    private static class CheckRedis implements Runnable {


        @Override
        public void run() {
            log.info(Thread.currentThread().getName() + "，第{}次进来", i);

            i++;

            if (i == 10) {
                try {
                    Thread.sleep(Integer.MAX_VALUE);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            process();
        }

        private void process() {
            executorService.execute(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
